﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using Smarly.Bussines.Extentions;
using Smarly.Bussines.Membership;
using Smarly.Core;
using Smarly.Core.Database;

namespace Smarly.Bussines.Model
{
	public class Book : ModelStateObject
	{

		internal Guid BookId { get; set; }

		[Required(ErrorMessage = "Поле не заполнено")]
		public string Author { get; set; }
		[Required(ErrorMessage = "Поле не заполнено")]
		public string CoverUrl { get; set; }

		public bool ExistPdf { get; set; }

		public BookTree Root { get; set; }


		[DatabaseValidation("HashTagExist", "Такой хэш тэг уже используется")]
		[DatabaseValidation("BookNotExist", "Не найдена текущая страница")]
		[Required(ErrorMessage = "Поле не заполнено")]
		public string HashTag { get; set; }
		[Required(ErrorMessage = "Поле не заполнено")]
		public string Title { get; set; }



		public List<Book> Get(SmarlyIdentity identity)
		{
			return SqlRepository.ExecuteProcedureReader("Text_Book_Get",
																					 new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@userId", Value = identity.UserId, Type = DbType.Guid},
			                                     	}, null,
																					 ReadGet);

		}

		private List<Book> ReadGet(IDataReader reader)
		{
			List<Book> result = new List<Book>();
			int batchNum = 0;
			do
			{
				switch (batchNum)
				{
					case 0:
						while (reader.Read())
						{
							var book = new Book
							{
								BookId = reader.GetGuid("BookId"),
								Author = reader.GetString("Author"),
								CoverUrl = reader.GetString("CoverUrl"),
							};
							result.Add(book);
						}
						break;
					case 1:
						List<BookTree> list = new List<BookTree>();
						Book currentBook = null;
						while (reader.Read())
						{
							var item = new BookTree
							{
								Id = reader.GetInt64("BookTreeId"),
								ParentId = reader.GetInt64OrNull("ParentBookTreeId") ?? -1,
								LeftKey = reader.GetInt32("LeftKey"),
								Level = reader.GetByte("Level"),
								IsHead = reader.GetBoolean("IsHead"),
								Text = reader.GetString("Text"),
								Url = reader.GetStringOrNull("Url"),
								Published = reader.GetBoolean("Published"),
							};

							Guid bookId = reader.GetGuid("BookId");
							if (currentBook == null || bookId != currentBook.BookId)
								currentBook = result.Single(x => x.BookId == bookId);

							item.Book = currentBook;

							list.Add(item);
						}

						foreach (var root in list.Where(x => x.ParentId == -1).ToList())
						{
							BookTree.CreateTree(root, list);
							root.Book.Root = root;
						}

						break;
					default:
						throw new ApplicationException("Additional batch select");

				}
				batchNum++;
			} while (reader.NextResult());

			return result;
		}

		public Book Post()
		{
			return SqlRepository.ExecuteProcedureReader("Text_Book_Create",
			                                            new List<SpParam>
				                                            {
					                                            new SpParam {Name = "@title", Value = Title, Type = DbType.String},
					                                            new SpParam {Name = "@author", Value = Author, Type = DbType.String},
					                                            new SpParam {Name = "@coverUrl", Value = CoverUrl, Type = DbType.String},
					                                            new SpParam {Name = "@hashTag", Value = HashTag, Type = DbType.String},
				                                            }, OnSqlInfoMessage,
			                                            (reader) => this);

		}


	}
}